import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 10000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * code为非200是抛错 可结合自己业务进行修改
    */
    if (response.status === 200) {
      const token = response.headers.authorization
      const data = response.data
      if (data.status === 200) {
        if (token) {
          store.dispatch('SaveToken', { token })
        }
        return data.data
      } else {
        Message({ message: data.message, type: 'error' })
        return Promise.reject(data.message)
      }
    } else if (response.status === 500) {
      console.log(response.data.data.data, 123)
      return response.data.data.data
    } else {
      console.log('status is not 200')
    }
  },
  error => {
    console.log(error)
    console.log(error.response, 8)
    if (error.response && error.response.status === 401) {
      // console.log(error.response)
      if (error.response.data && error.response.data.message) {
        Message({
          message: error.response.data.message,
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        Message({
          message: '登录超时，返回登录页',
          type: 'warning',
          duration: 5 * 1000
        })
      }
    } else if (error.response && error.response.data) {
      console.log('data')
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
